<template>
  <!--  链接-->
  <el-divider style="width: 100%"
    ><span style="font-size: 23px; font-family: '楷体'">用户端链接管理</span></el-divider
  ><br />
  <!--  搜索表单-->
  <el-form :inline="true" :model="linkName">
    <el-form-item label="链接主题">
      <el-input
        style="width: 400px"
        v-model="linkName"
        type="text"
        autocomplete="off"
        placeholder="输入搜索标题"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">搜索</el-button>
      <el-button type="info" @click="resetForm">清空</el-button>
    </el-form-item>
  </el-form>
  <div style="margin-left: 90%">
    <el-button type="success" style="width: 100px" @click="insertLink">+ 新 增</el-button>
  </div>
  <br />

  <!--  新增链接对话框-->
  <el-dialog v-model="dialogInsertVisible" center align-center :title="dialogName" width="40%">
    <el-form v-model="link" ref="linkRuleFormRef" :model="link" :rules="linkInfoRules" status-icon>
      <el-form-item label="链接主题" prop="linkName">
        <el-input
          maxlength="20"
          v-model="link.linkName"
          placeholder="请填写链接主题"
          clearable
          show-word-limit
        />
      </el-form-item>
      <br /><span style="font-size: 13px; color: #909399">图片尺寸建议 640 x 220 左右</span
      ><br /><br />
      <el-form-item label="链接图片" prop="linkImage">
        <el-upload
          class="avatar-uploader"
          :headers="token"
          action="/api/student/signup/upload"
          name="stuImage"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="link.linkImage" :src="link.linkImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus />链接图片</el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="链接地址" prop="linkUrl">
        <el-input v-model="link.linkUrl" placeholder="请填写链接地址" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogInsertVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveLink(linkRuleFormRef)">
          {{ dialogButton }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!--  链接列表-->
  <el-table :data="linkInfo" border>
    <el-table-column type="index" label="序号" width="60px" align="center" />
    <el-table-column property="linkName" label="链接主题" width="350px" align="center" />
    <el-table-column label="链接图片" align="center" width="200px">
      <template v-slot="row">
        <el-image :src="row.row.linkImage" style="width: 160px; height: 55px"></el-image>
      </template>
    </el-table-column>
    <el-table-column label="链接地址" align="center">
      <template v-slot="row">
        <el-link @click="openNew(row.row.linkUrl)">{{ row.row.linkUrl }}</el-link>
      </template>
    </el-table-column>
    <el-table-column property="createTime" label="创建时间" align="center" width="180px" />
    <el-table-column label="操作" align="center" width="180px">
      <template v-slot="row">
        <el-button type="primary" @click="updateLink(row.row.linkId)">编辑</el-button>
        <el-button type="danger" @click="sureDelete(row.row.linkId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElTable,
  FormInstance,
  FormRules,
  UploadProps
} from 'element-plus'
import { deleteLinkById, getLinkById, getLinkInfo, insert, update } from '@/apis/link'
import { getToken } from '@/utils/token'

const openNew = (url: string) => {
  window.open(url)
}
// 用于搜索和分页
const linkName = ref('')
const dialogInsertVisible = ref(false)
const token = ref({ token: getToken() })
const dialogName = ref()
const dialogButton = ref()

interface Link {
  linkId: number
  linkName: string
  linkImage: string
  linkUrl: string
  createTime: string
}

const linkInfo = ref<Link[]>([
  {
    linkId: 1,
    linkName: '测试链接1',
    linkImage: '测试1',
    linkUrl: 'https://element-plus.org/images/element-plus-logo.svg',
    createTime: '447'
  }
])

const link = ref<Link>({
  linkId: 1,
  linkName: '',
  linkImage: '',
  linkUrl: '',
  createTime: ''
})
const linkRuleFormRef = ref<FormInstance>()
const linkInfoRules = reactive<FormRules<typeof link>>({
  linkName: [{ required: true, message: '请填写链接主题名', trigger: 'burl' }],
  linkImage: [{ required: true, message: '请选择链接图片', trigger: 'burl' }],
  linkUrl: [{ required: true, message: '请选填写链接地址', trigger: 'burl' }]
})
const getInfo = () => {
  getLinkInfo(linkName.value).then((res) => {
    console.log('获取链接信息')
    if (res.data.code === 1) {
      console.log('获取成功')
      linkInfo.value = res.data.data
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
      console.log('获取失败')
    }
  })
}

onMounted(() => {
  getInfo()
})

const insertLink = () => {
  link.value = {}
  dialogName.value = '新增链接'
  dialogButton.value = '添加'
  dialogInsertVisible.value = true
}

const submitForm = () => {
  getInfo()
}
const resetForm = () => {
  linkName.value = ''
  getInfo()
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  link.value.linkImage = response.data
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (File) => {
  if (File.type !== 'image/jpeg') {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
    return false
  } else if (File.size / 1024 / 1024 > 2) {
    ElMessage.error('上传头像图片大小不能超过 2MB!!')
    return false
  }
  return true
}

const sureDelete = (linkId: number) => {
  ElMessageBox.confirm('确认删除该链接吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteLinkById(linkId).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '删除成功' })
          getInfo()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除' })
    })
}
const updateLink = (linkId: number) => {
  dialogName.value = '编辑链接'
  dialogButton.value = '保存'
  dialogInsertVisible.value = true
  getLinkById(linkId).then((res) => {
    if (res.data.code === 1) {
      link.value = res.data.data
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const saveLink = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (link.value.linkId != undefined) {
        // 编辑
        update(link.value).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '修改成功' })
            dialogInsertVisible.value = false
            getInfo()
            link.value = {}
          } else ElMessage({ type: 'error', message: res.data.msg })
        })
      } else {
        //插入
        insert(link.value).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '添加成功' })
            dialogInsertVisible.value = false
            getInfo()
            link.value = {}
          } else ElMessage({ type: 'error', message: res.data.msg })
        })
      }
    } else return false
  })
}
</script>
<style>
.avatar-uploader .avatar {
  width: 320px;
  height: 110px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 320px;
  height: 110px;
  text-align: center;
}
.el-icon {
  margin-left: 8px;
  margin-right: 8px;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-left: 8px;
  margin-right: 6px;
}
</style>
